package com.spzx.product.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.product.service.ISkuStockService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Description:
 *
 * @author Yanxinhao on 2024/12/28
 */
@Component
@Slf4j
public class ProductReceiver {

    @Autowired
    private ISkuStockService stockService;


    @SneakyThrows //lombok的注解，直接一次性将所有异常自动抛出
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT),
            value = @Queue(value = MqConst.QUEUE_UNLOCK,durable = "true"),
            key = MqConst.ROUTING_UNLOCK
    ))
    public void unlock(String orderNo,Message message, Channel channel){
        try {
            //打印日志
            log.info("[商品服务]监听解锁库存消息：{}",orderNo);
            //对商品进行解锁操作
            stockService.unlock(orderNo);
            //手动应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }

    }

    @SneakyThrows //lombok的注解，直接一次性将所有异常自动抛出
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT),
            value = @Queue(value = MqConst.QUEUE_MINUS,durable = "true"),
            key = MqConst.ROUTING_MINUS
    ))
    public void minusStock(Message message,String orderNo,Channel channel){
        //业务处理
        if (StringUtils.isNotEmpty(orderNo)){
            log.info("[商品服务]监听减库存消息：{}", orderNo);
            //扣减库存
            stockService.minus(orderNo);
        }

        //手动应答
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}